package tools

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"
	"crypto/md5"
)

//des加密

func DesEncrypt(origData, key []byte) ([]byte, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		//return nil, err
		return nil, err
	}
	origData = PKCS5Padding(origData, block.BlockSize())
	//origData = ZeroPadding(origData, block.BlockSize())
	//blockMode := cipher.NewCBCEncrypter(block, key)
	blockMode := cipher.NewCFBEncrypter(block, key)
	crypted := make([]byte, len(origData))
	//根据CryptBlocks方法的说明，如下方式初始化crypted也可以
	//crypted := origData
	//blockMode.CryptBlocks(crypted, origData)
	blockMode.XORKeyStream(crypted, origData)
	return crypted, nil
}

func PKCS5Padding(data []byte, size int) []byte {
	padding := size - len(data)%size
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(data, padtext...)
}

//	data := []byte("Hello, World!")
//	hash := md5.Sum(data)
//	fmt.Printf("MD5 hash: %x\n", hash)

func MD5(data []byte) []byte {
	hash := md5.Sum(data)
	return hash[:]
}
